package com.luhaoran.hrm.interceptor;

import com.luhaoran.hrm.exception.MyJsonValidationException;
import com.luhaoran.hrm.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
/**
 * 用户拦截器
 *
 * */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 在请求方法之前拦截设卡
     * @param request
     * @param response
     * @param handler
     * @return true:通行  false:拒绝
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            log.warn("token为空，认证失败");
            throw new MyJsonValidationException("token为空，认证失败");
        } else {
            String id = TokenUtils.verify(token);
            if (id == null) {
                log.warn("token错误，认证失败");
                throw new MyJsonValidationException("token错误，认证失败");
            } else {
                //把id加入当前request对象
                request.setAttribute("id",id);
                return true;
            }
        }
    }

}

